<?php


/**
 * 生产查询
 * @package  ajax
 * @subpackage  backend
 * @author   create by allen.qiang
 */

//引入商品营养成分类
quanli_require('module/base/goods/goodsNutrition.class.php');

//引入商品生产信息类
quanli_require('module/base/goods/goodsProduce.class.php');

//引入查询三级商品qs信息类
quanli_require('module/base/goods/quanliGoods.class.php');

//条形码生成类
quanli_include('module/base/common/quanliBarcode.class.php');

class ajax_productionSearch {

    //订单标识
    private $urgentArray = array(
        '0' => '普通',
        '1' => '加急',
        '2' => '重要',
        '3' => '普通'
    );

    //订单类型
    private $billTypeArray = array(
        '1' => '正常订单',
        '2' => '生日会蛋糕',
        '3' => '市场推广',
        '4' => '其他订单',
        '5' => '补偿订单',
        '6' => '测试订单',
        '7' => '招待赠送',
        '8' => '大客户订单',
        '9' => '试吃订单',
    );

    //订单状态
    private $billStatus = array(
    	//mod by yim.hu 20141121 FUN-BK-0035-订单状态优化 --start    		
//         '0' => '建立',
//         '1' => '确认',
//         '2' => '生产',
//         '3' => '入库',
//         '4' => '上车',
//         '5' => '下车',
//         '6' => '配送',
//         '7' => '完成',
//         '10' => '取消'
	    '0' => '未确认',
	    '1' => '已确认',
	    '2' => '已打印生产单',
	    '3' => '已质检入库',
	    '4' => '已上车',
	    '5' => '已下车',
	    '6' => '已出仓',//暂时没
	    '7' => '已完成',
	    '10' => '已取消' 
    	//mod by yim.hu 20141121 FUN-BK-0035-订单状态优化 --end	   		
    );

    public function execute() {

        if (isset($_REQUEST['operFlg']) && $_REQUEST['operFlg'] > 0) {

            switch ($_REQUEST['operFlg']) {

                case 1: //列表
                    $this->productionList();
                    break;

                case 2: //QS商标打印
                    $this->brandScanPrint();
                    break;

                case 3: //打印订单增加订单商品生产表bill_goods_product添加打印信息 订单商品表bill_goods打印信息  订单主表bill_master状态
                    $this->changeStatus();
                    break;

                case 4: //验证是否已打印
                    $this->verifyScanPrint();
                    break;

            }
        }
    }

    /*
     * 列表
     *
     * */
    public function productionList () {

        //查询条件选择了城市、配送站 则根据选择的城市、配送站查询
        if( isset($_REQUEST['cityID']) && is_numeric($_REQUEST['cityID']) && isset( $_REQUEST['distribution_id']) && is_numeric($_REQUEST['distribution_id'])){
            $_REQUEST['cityID'] = $_REQUEST['cityID'];
            $_REQUEST['distribution_id'] = $_REQUEST['distribution_id'];

        //查询条件选择了城市、没有选择配送站 则根据选择的城市、当前登录用户权限下的配送站查询
        }else if(isset($_REQUEST['cityID']) && is_numeric($_REQUEST['cityID']) && !isset( $_REQUEST['distribution_id']) || !is_numeric($_REQUEST['distribution_id']) ){
            $_REQUEST['cityID'] = $_REQUEST['cityID'];
            global $G_SHOP;
            $PS_LOGIN_SESSION =$G_SHOP->sessionCache_get('PS_LOGIN_SESSION');

            $distribution_id_array = $PS_LOGIN_SESSION['distribution'];//权限下的配送站id数组

            if( count($distribution_id_array) > 1){

                $distribution_id_arg = implode( ',',$distribution_id_array );

                $_REQUEST['extend'] = ' AND g.distribution_id IN ('.$distribution_id_arg.')';

            }else{
                $_REQUEST['distribution_id'] = $distribution_id_array[0];

            }

        //查询条件没有选择城市、没有选择配送站 则根据选择的城市、当前登录用户权限下的城市、配送站查询
        }else{
            global $G_SHOP;
            $PS_LOGIN_SESSION =$G_SHOP->sessionCache_get('PS_LOGIN_SESSION');

            $distribution_id_array = $PS_LOGIN_SESSION['distribution'];//权限下的配送站id数组

            if( count($distribution_id_array) > 1){

                $distribution_id_arg = implode( ',',$distribution_id_array );

                $_REQUEST['extend'] = ' AND distribution_id IN ('.$distribution_id_arg.')';

            }else{
                $_REQUEST['distribution_id'] = $distribution_id_array[0];

            }

        }

        //add by allen.qiang 20141104 FUN-BK-0014 代付单跳流程 ---start
        $_REQUEST['G_DFD_SKU'] = "DFD";//是不是代付单跳流程查询
        //add by allen.qiang 20141104 FUN-BK-0014 代付单跳流程 ---end

        //查找订单商品生产表数据
        $bill_array = $this->searchBillInfo( $_REQUEST ) ;


        //查询结果
        $result_array = array(
            'page' => $_REQUEST['page'],
            'total' => $_REQUEST['count'],
            'rows' => array()
        );

        if ($bill_array) {
            foreach ($bill_array as $key=>&$goodsInfo) {

                $operatorString = '<input type="checkbox" class="itemCheck" name="billArr[]" value="' . $goodsInfo['bill_goods_no'] . '" />';

                $result_array['rows'][] = array(
                    'id' => $goodsInfo['bill_goods_no'],
                    'cell' => array(
                        $operatorString,
                        $key+1,
                        $goodsInfo['cityName'],
                        $this->urgentArray[$goodsInfo['is_urgent']],
                        $this->billStatus[$goodsInfo['bill_status']],
                        $this->billTypeArray[$goodsInfo['billType']],
                        $goodsInfo['send_date'],
                        $goodsInfo['send_start_time'],
                        $goodsInfo['send_end_time'],
                        $goodsInfo['createTime'],
                        $goodsInfo['print_num'],
                        $goodsInfo['print_time'],
                        '<a href="javascript: void(0);" onclick="productSearch.billview(\''.$goodsInfo['bill_no'].'\');">'.$goodsInfo['bill_code'].'</a>',
                        $goodsInfo['distribution_name'],
                        $goodsInfo['product_code'],
                        $goodsInfo['goods_name'],
                        $goodsInfo['goods_spec'],
                        $goodsInfo['goods_amount'],
                        $goodsInfo['tableware_amount']?$goodsInfo['tableware_amount']:'',
                        $goodsInfo['birthday_card'],
                        $goodsInfo['segmentation']?$goodsInfo['segmentation']:'',
                        $goodsInfo['goods_remark']

                    )
                );
            }
        }

        echo json_encode($result_array);

    }


    /**
     * 查询订单商品生产表信息bill_goods_product
     * @param array $arg_array
     * @return null|array
     */
    public function searchBillInfo( &$arg_array ) {

        global $G_PGLOB;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //订单号
        if (isset($arg_array['bill_no']) && !empty($arg_array['bill_no'])) {
            $sql .= ' AND g.bill_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['bill_no'];
        }

        //订单编号后六位
        if (isset($arg_array['bill_code']) && !empty($arg_array['bill_code'])) {
            $sql .= ' AND g.bill_code LIKE ? ';
            $params_type .= 's';
            $params_array[] = '%'.$arg_array['bill_code']. '%';
        }

        //订单商品流水号
        if (isset($arg_array['bill_goods_no']) &&  !empty($arg_array['bill_goods_no'])) {
            $sql .= ' AND g.bill_goods_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['bill_goods_no'];
        }

        //城市ID
        if (isset($arg_array['cityID']) && is_numeric($arg_array['cityID'])) {
            $sql .= ' AND g.cityID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['cityID'];
        }

        //订单类型
        if(isset($arg_array['bill_type']) && !empty($arg_array['bill_type'])){
            if(strpos($arg_array['bill_type'],'all') !== false){
                $sql .= " AND g.billType IN (1,2,3,4,5,6,7,8,9)";
            }else{
                $sql .= " AND g.billType IN ( ".$arg_array['bill_type']." )";
            }
        }

        //订单状态
        if(isset($arg_array['billStatus']) && !empty($arg_array['billStatus'])){
            if(strpos($arg_array['billStatus'],'all') !== false){
                $sql .= " AND m.bill_status IN (1,2,3,4)";
            }else{
                $sql .= " AND m.bill_status IN ( ".$arg_array['billStatus']." )";
            }
        }

        //配送日期
        if (isset($arg_array['send_date']) && !empty($arg_array['send_date'])) {
            $sql .= ' AND g.send_date = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['send_date'];
        }

        //配送开始时间
        if (isset($arg_array['send_start_time']) && !empty($arg_array['send_start_time'])) {
            $sql .= ' AND g.send_start_time >= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['send_start_time'];
        }

        //配送结束时间
        if (isset($arg_array['send_start_time_end']) && !empty($arg_array['send_start_time_end'])) {
            $sql .= ' AND g.send_start_time <= ?  ';
            $params_type .= 's';
            $params_array[] = $arg_array['send_start_time_end'];
        }

        //配送站ID
        if (isset($arg_array['distribution_id']) && is_numeric($arg_array['distribution_id'])) {
            $sql .= ' AND g.distribution_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['distribution_id'];
        }

        //配送站名称
        if (isset($arg_array['distribution_name']) && !empty($arg_array['distribution_name'])) {
            $sql .= ' AND g.distribution_name = ?';
            $params_type .= 's';
            $params_array[] = encryptD($arg_array['distribution_name']);
        }

        //加急状态
        if (isset($arg_array['is_urgent']) && is_numeric($arg_array['is_urgent'])) {
            $sql .= ' AND g.is_urgent = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['is_urgent'];
        }

        //网购号
        if (isset($_REQUEST['goods_postID']) && is_numeric($arg_array['goods_postID'])) {
            $sql .= ' AND g.goods_postID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['goods_postID'];
        }


        //商家编码
        if (isset($arg_array['product_code']) && !empty($arg_array['product_code'])) {
            $sql .= ' AND g.product_code = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['product_code'];
        }

        //商品名称 /SKU / 商品ID  模糊查询
        if (isset($arg_array['sku']) && !empty($arg_array['sku'])) {
            $sql .= ' AND (g.goods_name like ? OR g.product_code =? OR g.goods_postID = ?) ';
            $params_type .= 'ssi';
            $params_array[] = '%'.$arg_array['sku'].'%';
            $params_array[] = $arg_array['sku'];
            $params_array[] = $arg_array['sku'];
        }

        //商品规格
        if (isset($arg_array['goods_spec']) && !empty($arg_array['goods_spec'])) {
            $sql .= ' AND g.goods_spec = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['goods_spec'];
        }

        //商品数量
        if (isset($arg_array['goods_amount']) && is_numeric($arg_array['goods_amount'])) {
            $sql .= ' AND g.goods_amount = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['goods_amount'];
        }

        //餐具数量
        if (isset($arg_array['tableware_amount']) && is_numeric($arg_array['tableware_amount'])) {
            $sql .= ' AND g.tableware_amount = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['tableware_amount'];
        }

        //生日牌
        if (isset($arg_array['birthday_card']) && is_numeric($arg_array['birthday_card'])) {
            if($arg_array['birthday_card'] == 1){ //状态为是 含生日牌
                $sql .= ' AND g.birthday_card IS NOT NULL AND g.birthday_card <> "" ';
            }else{
                $sql .= ' AND g.birthday_card = "" ';
            }
        }

        //切分状态
        if (isset($arg_array['segmentation']) && is_numeric($arg_array['segmentation'])) {
            if($arg_array['segmentation'] == 1){ //状态为是 切分
                $sql .= ' AND g.segmentation >= ?';
            }else{
                $sql .= ' AND g.segmentation = ?';
            }
            $params_type .= 'i';
            $params_array[] = $arg_array['segmentation'];

        }

        //是否打印
        if (isset($arg_array['print_num']) && is_numeric($arg_array['print_num'])) {
            if($arg_array['print_num'] == 1){ //状态为是 打印
                $sql .= ' AND g.print_num >= ?';
            }else{
                $sql .= ' AND g.print_num = ?';
            }
            $params_type .= 'i';
            $params_array[] = $arg_array['print_num'];

        }

        //拓展字段
        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        //add by allen.qiang 20141104 FUN-BK-0014 代付单跳流程 ---start
        if (isset($arg_array['G_DFD_SKU']) && !empty($arg_array['G_DFD_SKU']) && $arg_array['G_DFD_SKU']=="DFD") { //是不是代付单跳流程查询
            $sql .= " AND g.product_code NOT IN (".G_TPT_SKU.")";//排除代付单的特殊商品编码
        }
        //add by allen.qiang 20141104 FUN-BK-0014 代付单跳流程 ---end


        //add by sunqiang 下午茶订单不走生产 该模块需重新规划 start
        $sql .= ' AND m.billPlatform !=3 ';

        //add by sunqiang 下午茶订单不走生产 该模块需重新规划　end




        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM bill_goods_product g INNER JOIN bill_master m ON m.bill_code = g.bill_code ' . $sql;

                $count_array = &$G_PGLOB->DBCA->stmt_query($search_sql, $params_type, $params_array);

                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                if($_REQUEST['count'] < $_REQUEST['rp']){
                    $_REQUEST['page'] = 1;
                }

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT g.*, m.bill_status,m.bill_code FROM bill_goods_product g
                                   INNER JOIN bill_master m ON m.bill_code = g.bill_code' . $sql;
            $temp_item_array = $G_PGLOB->DBCA->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array) {
                return null;
            }

            foreach ($temp_item_array as $bill) {

                    $item_array[] = array(

                        'uuid' => $bill->uuid,
                        'creator' => $bill->creator,
                        'createTime' => $bill->createTime,
                        'bill_no' => (string)$bill->bill_no,
                        'bill_code' => (string)$bill->bill_code,
                        'bill_goods_no' => (string)$bill->bill_goods_no,
                        'cityID' => $bill->cityID,
                        'cityName' => $bill->cityName,
                        'billType' => $bill->billType,
                        'bill_status' => $bill->bill_status,
                        'send_date' => $bill->send_date,
                        'send_start_time' => $bill->send_start_time,
                        'send_end_time' => $bill->send_end_time,
                        'distribution_id' => $bill->distribution_id,
                        'distribution_name' => $bill->distribution_name,
                        'is_urgent' => $bill->is_urgent,
                        'goods_postID' => $bill->goods_postID,
                        'product_code' => $bill->product_code,
                        'goods_name' => $bill->goods_name,
                        'goods_spec' => $bill->goods_spec,
                        'goods_amount' => $bill->goods_amount,

                        'tableware_amount' => $bill->tableware_amount,
                        'extra_tableware_amount'=>$bill->extra_tableware_amount,
                        'candle_amount'=>$bill->candle_amount,
                        'extra_candle_amount'=>$bill->extra_candle_amount,

                        'birthday_card' => $bill->birthday_card,
                        'segmentation' => $bill->segmentation,
                        'goods_remark' => $bill->goods_remark,
                        'print_num' => $bill->print_num,
                        'print_operator' => $bill->print_operator,
                        'print_time' => $bill->print_time



                    );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }


    /*
     *
     * 打印QS商标信息
     */
    private function brandScanPrint() {

        if (!isset($_REQUEST['print_array']) || empty($_REQUEST['print_array'])) {
            returnJsonData('参数错误');
        }

        quanli_require('module/base/bill/billProduct.class.php');

        //实例订单商品生产类
        $billProduct = new billProduct();

        //订单商品打印
        $result_array = $billProduct->printGoodsQs( $_REQUEST['print_array'] );

        returnJsonData($result_array['message'], $result_array['code']);

    }

    /**
     *  打印订单修改订单状态
     */
    public function changeStatus() {

        //error_log('订单商品打印开始：' . date(G_DEFAULT_DATETIME_FORMAT));

        if (!isset($_REQUEST['print_array']) || empty($_REQUEST['print_array'])) {
            returnJsonData('参数错误');
        }

        //error_log('订单商品打印全部流水号：' . implode(',', $_REQUEST['print_array']));

        quanli_require('module/base/bill/billProduct.class.php');

        //实例订单商品生产类
        $billProduct = new billProduct();

        //订单商品打印
        $result_array = $billProduct->printGoodsQs( $_REQUEST['print_array'] );
//        foreach($_REQUEST['print_array'] as &$bill_goods_no) {
//            $result_array = $billProduct->printGoodsQs( $bill_goods_no );
//        }

        //error_log('订单商品打印结束：' . date(G_DEFAULT_DATETIME_FORMAT));
        returnJsonData($result_array['message'], $result_array['code']);

    }


    /*
   *
   * 验证是否已打印
   */
    private function verifyScanPrint(){

        global $G_PGLOB;

        //统计已打印的订单数据

        $errorNum = 0;

        if (empty($_REQUEST['printArr']) || !is_array( $_REQUEST['printArr'] )) {
            returnJsonData( '请选择要打印的数据',400);
        }

        $bill_code_array =array(); //订单编号数组
        foreach ($_REQUEST['printArr'] as $bill_goods_no) {

            //查询打印商品信息
            $arg_array = array(
                'bill_goods_no' => $bill_goods_no
            );
            $temp_goods_array = $this->searchBillInfo( $arg_array );


            if( $temp_goods_array ){
                if($temp_goods_array[0]['print_num'] > 0){
                    $errorNum++;
                    if( !in_array($temp_goods_array[0]['bill_code'], $bill_code_array )){
                        array_push( $bill_code_array, $temp_goods_array[0]['bill_code'] );
                    }
                }

            }
        }
//        echo '<pre>';
//        print_r( $bill_code_array );exit;
        if($errorNum > 0 ){
            $bill_code_array_count = count( $bill_code_array );
            if ($bill_code_array_count > 1){
                $bill_code_str = implode('],[',$bill_code_array);
            }else{
                $bill_code_str = $bill_code_array[0];
            }
            returnJsonData('包含打印过的<b> '.$errorNum.' </b>个订单,订单编号为[' .$bill_code_str. ']，是否再次打印？',202);
        }else{
            returnJsonData('ok',200);
        }

    }

}
